'use strict';

const Service = require('egg').Service;

const { formatPage } = require('../../utils/index');

const _ = require('lodash');
// 默认返回的用户基本信息字段
const { ARTICLE_DEFAULT_MODEL, ARTICLE_CANUPDATE_MODEL } = require('../../utils/common');

class ArticleService extends Service {
	/**
	 * 分页查询文章数据
	 * @returns { Object } { count : 总数目 , rows : [] 查询的数据结果}
	 */
	async list({ categoryId, title = '' }, { currentPage, pageNumber }) {
		currentPage = currentPage || 1;
		pageNumber = pageNumber || 10;
		const { offset, limit } = formatPage(currentPage, pageNumber);
		const Op = this.app.Sequelize.Op;
		// 校验文章类型 传入的是否为 数组类型的

		const queryParams = {
			limit,
			offset,
			where: {},
			order: [['createTime', 'DESC']]
		};

		// 根据文章题目查询文章数据
		if (title) {
			queryParams.where.title = {
				[Op.like]: `%${title}%`
			};
		}
		// 传入文章类型查询
		if (categoryId ) {
			queryParams.where.categoryId = categoryId;
		}

		// 通过 findAndCountAll 返回查询的结果和 所有的结果数
		const result = await this.ctx.model.Article.findAndCountAll(queryParams);

		return {
			page: {
				currentPage: currentPage,
				pageNumber: pageNumber,
				offset: offset,
				limit: limit,
				totalNumber: result.count
			},
			list: result.rows
		};
	}

	async info(id) {
		if (!id) return null;
		const { sequelize } = this.app;

		return await this.ctx.model.Article.findOne({
			attributes: ARTICLE_DEFAULT_MODEL,
			where: {
				id: id
			}
		});
	}

	async deleteArticleById(id) {
		if (!id) return null;
		return await this.ctx.model.Article.destroy({
			where: {
				id: id
			}
		});
	}

	async updateArticleInfoById(params) {
		let id = params.id;
		if (!id) return null;
		// 只能修改 ARTICLE_CANUPDATE_MODEL 中指定的属性的值
		return await this.ctx.model.Article.update(_.pick(params, ARTICLE_CANUPDATE_MODEL), {
			where: {
				id: id
			}
		});
	}
}

module.exports = ArticleService;
